let axios = require("axios")
let cheerio = require("cheerio")

require("./connect.js")

let {
    Book
} = require("./mod/bookcover.js")
let {
    Chapter
} = require("./mod/chapter.js")


var baseurl = "http://www.shuquge.com/"
//获取当前页的书籍基本信息
async function getPage(baseurl) {
    let res = await axios.get(baseurl)
    let $ = cheerio.load(res.data)
    // console.log(res)

    // 获取所有书籍的li
    $("body > div.nav > ul > li").each( (index, value) => {
        if (index > 0 && index < 8) {
            let next_url = $(value).find("a").attr("href") //小说的分类链接
            let book_type = $(value).first("a").text().trim()  //小说分类
            //根据分类链接跳转到推荐的book页
            // setTimeout(() => {
            //     getbookmulu(next_url, book_type)
            // }, index * 20*1000)
             getbookmulu(next_url, book_type)
        }
    })
}

// 根据分类url 跳转到具体的小说目录页面
async function getbookmulu(bookmuluurl, book_type) {
    let res = await axios.get(bookmuluurl)
    let $ = cheerio.load(res.data)
    $("body > div.wrap > div.up > div.r.bd > ul > li").each( (index, value) => {
        let nextbook_url = $(value).find("a").attr("href")  //获取推荐的小说链接
        let book_title = $(value).find("a").text().trim()  //获取推荐的小说名字
        // console.log(book_title)
        //根据分类链接跳转到推荐的book页

         getchaptermulu(nextbook_url, book_title, book_type)

    })
}

// 根据book_url 跳转到具体的小说chapters页面
async function getchaptermulu(bookmuluurl, book_title, book_type) {
    let res = await axios.get(bookmuluurl)
    let $ = cheerio.load(res.data)
    bookmuluurl = bookmuluurl.replace("index.html", "")

    let book_author = $("body > div.book > div.info > div.small > span:nth-child(1)").text().trim()
    let book_coverurl = $("body > div.book > div.info > div.cover > img").attr("src").trim()
    let book_describe = $("body > div.book > div.info > div.intro").html().trim()
    let book_number = $("body > div.book > div.info > div.small > span:nth-child(4)").text().trim()
    



    let url_arr=[]
    $("body > div.listmain > dl > dd").each( (index, value) => {
        let chapter_url = $(value).find("a").attr("href")  //获取小说每个chapter链接
        let chapter_title = $(value).find("a").text()
       
        chapter_url = bookmuluurl + chapter_url
        let obj={
            chapter_url:chapter_url,
            chapter_title:chapter_title
        }
        url_arr.push(obj)
    })

    //保存书本的封面信息
    let admin = new Book({
        book_author,
        book_title,
        book_coverurl,
        book_number,
        book_type,
        book_describe,
        url_arr
    })
    try {
        admin.save()
    } catch (err) {
        console.log("保存书本基本信息出错")
    }
}





getPage(baseurl)